<template>
  <el-card>
    <div slot="header">
      <span>查看考察报告</span>
    </div>
    <el-row>
      <ReportForm
        disabled
        :colNumOfRow="2"
        :formData.sync="baseInfoForm"
        ref="baseInfoForm"
        refName="base-info-form"
        :formFields="BASE_INFO_FIELDS" />
    </el-row>
    <el-divider />
    <el-row>
      <el-tabs type="card" v-model="activateName">
        <el-tab-pane label="基本信息" name="基本信息" v-if="showBasicInfo || showProductionInfo">
          <el-card>
            <el-divider v-if="showBasicInfo" content-position="left"><h4>基础信息</h4></el-divider>
            <ReportForm
              disabled
              :formData.sync="basicInfoForm"
              :oldValue="basicInfoFormOld"
              ref="basicInfoForm"
              refName="basic-info-form"
              :formFields="filterFiles(BASIC_INFO_VIEW_FIELDS)" />
            <el-divider v-if="showProductionInfo" content-position="left"><h4>生产信息</h4></el-divider>
            <ReportForm
              disabled
              :formData.sync="productionInfoForm"
              :oldValue="productionInfoFormOld"
              ref="productionInfoForm"
              refName="production-info-form"
              :formFields="filterFiles(PRODUCTION_INFO_FIELDS)" />
          </el-card>
        </el-tab-pane>
        <el-tab-pane v-if="planInfo.targetList.includes(1)" label="人员信息" name="人员信息">
          <SupplyUserTable ref="supplyUserInfo" :isView="true" :supplierUserList="supplierPersonList" />
        </el-tab-pane>
        <el-tab-pane v-if="showProducInfo" label="商品信息" name="商品信息">
          <el-card>
            <el-divider content-position="left"><h4>商品信息</h4></el-divider>
            <ReportForm
              :formData.sync="productInfoForm"
              :oldValue="productInfoFormOld"
              ref="productInfoForm"
              refName="product-info-form"
              :formFields="filterFiles(PRODUCT_INFO_VIEW_FIELDS)" />
          </el-card>
        </el-tab-pane>
        <el-tab-pane v-if="showManagementInfo" label="管理信息" name="管理信息">
          <el-card>
            <el-divider content-position="left"><h4>管理信息</h4></el-divider>
            <ReportForm
              disabled
              :formData.sync="managementInfoForm"
              :oldValue="managementInfoFormOld"
              ref="managementInfoForm"
              refName="management-info-form"
              :formFields="filterFiles(MANAGEMENT_INFO_FIELDS)" />
          </el-card>
        </el-tab-pane>
        <el-tab-pane v-if="showBillingInfo || showFinancialInfo || showQualityInfo || showRebateInfo || showDeliveryInfo" label="合同信息" name="合同信息">
          <el-card>
            <el-divider v-if="showBillingInfo" content-position="left"><h4>结算信息</h4></el-divider>
            <ReportForm
              disabled
              :formData.sync="billingInfoForm"
              :oldValue="billingInfoFormOld"
              ref="billingInfoForm"
              refName="billing-info-form"
              :formFields="filterFiles(CONTRACT_BILLING_INFO_FIELDS)" />
            <el-divider v-if="showBillingInfo" content-position="left"><h4>结算方式</h4></el-divider>
            <SettlementMethod v-if="showBillingInfo" id="billing-method-form" ref="billingMethodList" :showTitle="false" :readonly="true" :dataSource="supplierSettlementList" />
            <ReportForm
              style="margin-top: 10px"
              disabled
              :formData.sync="billingMethodInfoForm"
              ref="billingMethodInfoForm"
              refName="billing-method-info-form"
              :formFields="filterFiles(BILLING_METHOD_FIELDS)" />
            <el-divider v-if="showFinancialInfo" content-position="left"><h4>财务信息</h4></el-divider>
            <ReportForm
              disabled
              :formData.sync="financialInfoForm"
              :oldValue="financialInfoFormOld"
              ref="financialInfoForm"
              refName="financial-info-form"
              :formFields="filterFiles(CONTRACT_FINANCIAL_INFO_FIELDS)" />
            <el-divider v-if="showFinancialInfo && isQualifiedSupplier" content-position="left"><h4>原材料信息</h4></el-divider>
            <RawMaterialInfo
              v-if="showFinancialInfo && isQualifiedSupplier"
              readonly
              id="raw-material-info"
              ref="rawMaterialInfo"
              :dataSource="supplierRawMaterialList"
              :contractInfo="financialInfoForm || {}"
            />
            <el-divider v-if="showQualityInfo" content-position="left"><h4>铺底质保信息</h4></el-divider>
            <ReportForm
              disabled
              :formData.sync="qualityInfoForm"
              :oldValue="qualityInfoFormOld"
              ref="qualityInfoForm"
              refName="quality-info-form"
              :formFields="filterFiles(CONTRACT_QUALITY_INFO_FIELDS)" />
            <el-divider v-if="showRebateInfo" content-position="left"><h4>返利信息</h4></el-divider>
            <ReportForm
              disabled
              :formData.sync="rebateInfoForm"
              :oldValue="rebateInfoFormOld"
              ref="rebateInfoForm"
              refName="rebate-info-form"
              :formFields="filterFiles(CONTRACT_REBATE_INFO_FIELDS)" />
            <el-divider v-if="showDeliveryInfo" content-position="left"><h4>交付信息</h4></el-divider>
            <ReportForm
              disabled
              :formData.sync="deliveryInfoForm"
              :oldValue="deliveryInfoFormOld"
              ref="deliveryInfoForm"
              refName="delivery-info-form"
              :formFields="filterFiles(CONTRACT_DELIVERY_INFO_FIELDS)" />
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </el-row>
    <el-row type="flex" justify="center" class="formFooter">
      <el-button @click="handleCancel">返回</el-button>
    </el-row>
  </el-card>
</template>
<script>
import ReportForm from './components/BaseForm' // 表单组件
import SupplyUserTable from './components/SupplyUserTable' // 人员信息
import SettlementMethod from '@/pages/supplier/components/settlementMethod' // 结算方式组件
import RawMaterialInfo from '@/pages/supplier/components/rawMaterialInfo' // 原材料信息组件
import {
  BASE_INFO_FIELDS,
  BASIC_INFO_VIEW_FIELDS, // 基本信息 基础信息
  PRODUCTION_INFO_FIELDS, // 基本信息 生产信息
  PRODUCT_INFO_VIEW_FIELDS, // 商品信息
  MANAGEMENT_INFO_FIELDS, // 管理信息
  CONTRACT_BILLING_INFO_FIELDS,
  BILLING_METHOD_FIELDS,
  CONTRACT_FINANCIAL_INFO_FIELDS,
  CONTRACT_QUALITY_INFO_FIELDS,
  CONTRACT_REBATE_INFO_FIELDS,
  CONTRACT_DELIVERY_INFO_FIELDS,
} from './constants/viewReport'
import {
  queryReportDetailService,
  queryReportDiffValService
} from '@api/supplier/returnVisteManage';
import { queryItemsByDictIdsService, querySysTypeByDictIdsService, queryManageAreaService } from '@api/supplier/components';
import { isResponseSuccess } from '@/pages/supplier/utils/bizUtils';

export default {
  components: {
    ReportForm,
    SupplyUserTable,
    SettlementMethod,
    RawMaterialInfo
  },
  data () {
    return {
      reportId: null,
      supplierClassify: '',
      submitLoading: false,
      tabList: ['基本信息', '人员信息', '商品信息', '管理信息', '合同信息'],
      activateName: '基本信息',
      BASE_INFO_FIELDS,
      BASIC_INFO_VIEW_FIELDS,
      PRODUCTION_INFO_FIELDS,
      PRODUCT_INFO_VIEW_FIELDS,
      MANAGEMENT_INFO_FIELDS,
      CONTRACT_BILLING_INFO_FIELDS,
      BILLING_METHOD_FIELDS,
      CONTRACT_FINANCIAL_INFO_FIELDS,
      CONTRACT_QUALITY_INFO_FIELDS,
      CONTRACT_REBATE_INFO_FIELDS,
      CONTRACT_DELIVERY_INFO_FIELDS,
      planInfo: {
        planId: '',
        supplierId: '',
        targetList: [],
        type: null
      },
      baseInfoForm: {
        visitTime: '',
        negotiationDetail: '',
        inspectCompleteTime: '',
        disposalMeasures: '',
        subsequentBacklog: '',
        subsequentBacklogName: '',
        backlogExplain: '',
        planCompleteTime: '',
      },
      basicInfoForm: {}, // 基础信息
      basicInfoFormOld: {},
      productionInfoForm: {}, // 生产信息
      productionInfoFormOld: {},
      productInfoForm: {}, // 商品信息
      productInfoFormOld: {},
      managementInfoForm: {}, // 管理信息
      managementInfoFormOld: {},
      billingInfoForm: {}, // 结算信息
      billingInfoFormOld: {},
      billingMethodInfoForm: {}, // 结算方式
      financialInfoForm: {}, // 财务信息
      financialInfoFormOld: {},
      qualityInfoForm: {}, // 铺底质保信息
      qualityInfoFormOld: {},
      rebateInfoForm: {}, // 返利信息
      rebateInfoFormOld: {},
      deliveryInfoForm: {}, // 交付信息,
      deliveryInfoFormOld: {},
      supplierPersonList: [], // 供应商人员信息
      supplierSettlementList: [], // 结算方式
      supplierRawMaterialList: [], // 原材料信息
    }
  },
  computed: {
    isQualifiedSupplier () {
      return this.supplierClassify == '40332'
    },
    showBasicInfo () {
      return this.filterFiles(BASIC_INFO_VIEW_FIELDS).length;
    },
    showProductionInfo () {
      return this.filterFiles(PRODUCTION_INFO_FIELDS).length;
    },
    showProducInfo () {
      return this.filterFiles(PRODUCT_INFO_VIEW_FIELDS).length;
    },
    showManagementInfo () {
      return this.filterFiles(MANAGEMENT_INFO_FIELDS).length;
    },
    // 合同信息
    showBillingInfo () {
      return this.filterFiles(CONTRACT_BILLING_INFO_FIELDS).length;
    },
    showFinancialInfo () {
      return this.filterFiles(CONTRACT_FINANCIAL_INFO_FIELDS).length;
    },
    showQualityInfo () {
      return this.filterFiles(CONTRACT_QUALITY_INFO_FIELDS).length;
    },
    showRebateInfo () {
      return this.filterFiles(CONTRACT_REBATE_INFO_FIELDS).length;
    },
    showDeliveryInfo () {
      return this.filterFiles(CONTRACT_DELIVERY_INFO_FIELDS).length;
    },
  },
  created () {
    const { planId, supplierId, targetList, type } = this.$route.query;
    this.planInfo = {
      planId,
      supplierId,
      targetList,
      type
    }
    if (this.planInfo.planId) {
      this.getDetailData()
    }
    this.initItemOptions()
    this.initTabName()
  },
  methods: {
    initTabName () {
      // ['基本信息', '人员信息', '商品信息', '管理信息', '合同信息']
      if (this.showBasicInfo || this.showProductionInfo) {
        this.activateName = this.tabList[0]
      } else if (this.showProducInfo) {
        this.activateName = this.tabList[2]
      } else if (this.showManagementInfo) {
        this.activateName = this.tabList[3]
      } else if (this.showBillingInfo || this.showFinancialInfo || this.showQualityInfo || this.showRebateInfo || this.showDeliveryInfo) {
        this.activateName = this.tabList[4]
      }
    },
    // 初始化 options
    initItemOptions () {
      let files = [
        ...this.filterFiles(BASIC_INFO_VIEW_FIELDS),
        ...this.filterFiles(PRODUCT_INFO_VIEW_FIELDS),
        ...this.filterFiles(MANAGEMENT_INFO_FIELDS),
        ...this.filterFiles(CONTRACT_BILLING_INFO_FIELDS),
        ...this.filterFiles(BILLING_METHOD_FIELDS),
        ...this.filterFiles(CONTRACT_FINANCIAL_INFO_FIELDS),
        ...this.filterFiles(CONTRACT_QUALITY_INFO_FIELDS),
        ...this.filterFiles(CONTRACT_REBATE_INFO_FIELDS),
        ...this.filterFiles(CONTRACT_DELIVERY_INFO_FIELDS),
      ]
      let masterIds = []
      let otherIds = []
      files.map((item) => {
        if (item.dictId && item.isMaster && !masterIds.includes(item.dictId)) {
          masterIds.push(item.dictId)
        } else if (item.dictId && !item.isMaster && !otherIds.includes(item.dictId)) {
          otherIds.push(item.dictId)
        }
      })
      Promise.all([
        this.queryOptionsByMaster(masterIds),
        this.queryOptionsBySupply(otherIds),
        this.queryManageAreaList()
      ]).then(([masterData, supplyData, manageAreaData]) => {
        const filesObj = Object.assign({}, masterData, supplyData, manageAreaData)
        files.forEach((item) => {
          if (item.dictId) {
            Object.keys(filesObj).forEach((ele) => {
              if (item.dictId == ele) {
                item.options = filesObj[ele]
              }
            })
          }
        })
      }).catch(() => {
      })
    },
    // 通过主数据获取
    async queryOptionsByMaster (ids) {
      const { result } = await querySysTypeByDictIdsService({ itemIds: ids.join(',') })
      return result;
    },
    // 通过供应商获取
    async queryOptionsBySupply (ids) {
      const { result } = await queryItemsByDictIdsService(ids)
      return result;
    },
    // 获取管理区域
    async queryManageAreaList () {
      const { result } = await queryManageAreaService()
      result.forEach(item => {
        item.manageAreaId = Number(item.manageAreaId)
      })
      return { 10000: result };
    },
    // 根据考察目的过滤Tab信息
    filterFiles (files) {
      const { targetList } = this.planInfo;
      if (targetList.length) {
        return files.filter(item => targetList.includes(item.target) || !item.target)
      }
    },
    // 获取报告详情
    getDetailData () {
      queryReportDetailService({ ...this.planInfo }).then((res) => {
        if (isResponseSuccess(res)) {
          const { result } = res;
          this.reportId = result.reportId;
          this.supplierClassify = result.supplierClassify;
          if (result.supplier || result.supplierContract || result.supplierPersonList) {
            const {
              visitTime, negotiationDetail, inspectCompleteTime, disposalMeasures, subsequentBacklog,
              subsequentBacklogName, backlogExplain, planCompleteTime, supplier, supplierContract,
              supplierPersonList, supplierSettlementList, supplierRawMaterialList
            } = result;
            this.baseInfoForm = {
              visitTime,
              negotiationDetail,
              inspectCompleteTime,
              disposalMeasures,
              subsequentBacklog,
              subsequentBacklogName,
              backlogExplain,
              planCompleteTime,
            }
            let formData = {
              supplier: supplier ? JSON.parse(supplier) : {},
              supplierContract: supplierContract ? JSON.parse(supplierContract) : {},
              supplierPersonList: supplierPersonList ? JSON.parse(supplierPersonList) : [],
              supplierSettlementList: supplierSettlementList ? JSON.parse(supplierSettlementList) : [],
              supplierRawMaterialList: supplierRawMaterialList ? JSON.parse(supplierRawMaterialList) : [],
            }
            console.log(formData)
            this.handleFillFormData(formData)
          }
        }
        this.getDiffData()
      })
    },
    // 获取报告变动值
    getDiffData () {
      queryReportDiffValService({ reportId: this.reportId }).then(res => {
        if (isResponseSuccess(res)) {
          if (res.result) {
            const { supplier, supplierContract } = res.result
            this.basicInfoFormOld = this.filterArrKeys(supplier, BASIC_INFO_VIEW_FIELDS)
            this.productionInfoFormOld = this.filterArrKeys(supplier, PRODUCTION_INFO_FIELDS)
            this.productInfoFormOld = this.filterArrKeys(supplier, PRODUCT_INFO_VIEW_FIELDS)
            this.managementInfoFormOld = this.filterArrKeys(supplier, MANAGEMENT_INFO_FIELDS)
            this.billingInfoFormOld = this.filterArrKeys(supplierContract, CONTRACT_BILLING_INFO_FIELDS)
            this.financialInfoFormOld = this.filterArrKeys(supplierContract, CONTRACT_FINANCIAL_INFO_FIELDS)
            this.qualityInfoFormOld = this.filterArrKeys(supplierContract, CONTRACT_QUALITY_INFO_FIELDS)
            this.rebateInfoFormOld = this.filterArrKeys(supplierContract, CONTRACT_REBATE_INFO_FIELDS)
            this.deliveryInfoFormOld = this.filterArrKeys(supplierContract, CONTRACT_DELIVERY_INFO_FIELDS)
          }
        }
      })
    },
    // 表单数据回填
    handleFillFormData (result) {
      const { supplier, supplierContract, supplierPersonList, supplierSettlementList, supplierRawMaterialList } = result;
      // 供应商人员信息
      this.supplierPersonList = supplierPersonList;
      // 结算方式
      this.supplierSettlementList = supplierSettlementList;
      this.supplierRawMaterialList = supplierRawMaterialList;
      // 基础信息
      this.basicInfoForm = Object.assign({}, this.basicInfoForm, { ...this.filterObjKeys(supplier, BASIC_INFO_VIEW_FIELDS) })
      // 生产信息
      this.productionInfoForm = Object.assign({}, this.productionInfoForm, { ...this.filterObjKeys(supplier, PRODUCTION_INFO_FIELDS) })
      // 商品信息
      this.productInfoForm = Object.assign({}, this.productInfoForm, { ...this.filterObjKeys(supplier, PRODUCT_INFO_VIEW_FIELDS) })
      // 管理信息
      this.managementInfoForm = Object.assign({}, this.managementInfoForm, { ...this.filterObjKeys(supplier, MANAGEMENT_INFO_FIELDS) })
      // 结算信息
      this.billingInfoForm = Object.assign({}, this.billingInfoForm, { ...this.filterObjKeys(supplierContract, CONTRACT_BILLING_INFO_FIELDS) })
      this.billingMethodInfoForm = Object.assign({}, this.billingMethodInfoForm, { ...this.filterObjKeys(supplierContract, BILLING_METHOD_FIELDS) })
      // 财务信息
      this.financialInfoForm = Object.assign({}, this.financialInfoForm, { ...this.filterObjKeys(supplierContract, CONTRACT_FINANCIAL_INFO_FIELDS) })
      // 铺底质保信息
      this.qualityInfoForm = Object.assign({}, this.qualityInfoForm, { ...this.filterObjKeys(supplierContract, CONTRACT_QUALITY_INFO_FIELDS) })
      // 返利信息
      this.rebateInfoForm = Object.assign({}, this.rebateInfoForm, { ...this.filterObjKeys(supplierContract, CONTRACT_REBATE_INFO_FIELDS) })
      // 交付信息
      this.deliveryInfoForm = Object.assign({}, this.deliveryInfoForm, { ...this.filterObjKeys(supplierContract, CONTRACT_DELIVERY_INFO_FIELDS) })
    },
    // 取消
    handleCancel () {
      this.$router.go(-1);
    },
    // 过滤对象中指定的key
    filterObjKeys (obj, fileObj) {
      let keys = this.filterFiles(fileObj).map((item) => item.prop);
      return Object.keys(obj).reduce((newData, key) => {
        if (keys.includes(key)) {
          newData[key] = obj[key];
        }
        return newData;
      }, {});
    },
    // 过滤list中指定的key
    filterArrKeys (arr, fileObj) {
      let keys = this.filterFiles(fileObj).map((item) => item.prop);
      return arr.reduce((newData, ele) => {
        if (keys.includes(ele.fieldName)) {
          newData[ele.fieldName] = ele.secondVal;
        }
        return newData;
      }, {});
    },
  }
};
</script>
<style lang="less" scoped>
  /deep/.el-input.is-disabled .el-input__inner, /deep/.el-textarea.is-disabled .el-textarea__inner {
    background-color: #fff;
    border-color: #E4E7ED;
    color: #606266;
  }
  .formFooter {
    margin-top: 10px;
  }
</style>
